var express = require('express');
var router = express.Router();
var daoHelper = require('../dao');
var commonUtil = require('../commonUtil'),
    beanUtil = require('../utils/beanUtil'),
    pathVarRegx = /\/manage-([^/]+)\/?/;

/* GET manage listing. */
router.get('/', function (req, res, next) {
    var mainMenu = {}, ifMenus = {}, result = [], dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    if(!pathInfo){
        res.render('error', {
            message: 'invalid path',
            error: req.originalUrl
        });
        return;
    }

    dao = daoHelper.getDao(pathInfo[1]);

    dao.getInterfaces(0).then(function (ifs) {
        commonUtil.each(ifs, function (_, ifObj) {
            ifObj = ifObj.toObject();
            ifObj.ifs = [];
            mainMenu[ifObj.interfaceId] = ifObj;
            result.push(ifObj);
        });
        return dao.getInterfaces(1);
    }).then(function (ifs) {
        commonUtil.each(ifs, function (_, ifObj) {
            ifObj = ifObj.toObject();
            ifMenus[ifObj.interfaceId] = ifObj;
            mainMenu[ifObj.parentId] && mainMenu[ifObj.parentId].ifs.push(ifObj);
        });

        return dao.getAllDetail();
    }).then(function (ifDetails) {
        commonUtil.each(ifDetails, function (_, ifDetail) {
            ifDetail = ifDetail.toObject();
            ifMenus[ifDetail.interfaceId].detailInfo = ifDetail;
        });

        res.render('manage', {list : result, apps : req.authApps});
    }).then(null, function(err){
        res.render('error', {
            message: err.message,
            error: err
        });
    });
});

router.post('/saveModule', function (req, res, next) {
    var recObj = req.body, saveObj = {
        interfaceId : recObj.mId,
        code : recObj.mCode,
        name : recObj.mName,
        order: recObj.mOrder,
        depth: 0
    }, promise, dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    if(!pathInfo){
        res.render('error', {
            message: 'invalid path',
            error: req.originalUrl
        });
        return;
    }

    dao = daoHelper.getDao(pathInfo[1]);

    if(saveObj.interfaceId){
        promise = dao.updateModule(saveObj);
    }else {
        saveObj.interfaceId = commonUtil.uuid(16, 16);
        saveObj.createDate = new Date();
        promise = dao.saveModule(saveObj);
    }

    promise.then(function(){
        res.end(JSON.stringify({suc : true}));
    }).then(null, function(err){
        res.end(JSON.stringify({suc : false, err : err}));
    });

});

router.post('/delModule/:id', function(req, res){
    var result, id = req.params.id, dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    dao = daoHelper.getDao(pathInfo[1]);

    dao.getInterfacesByModuleId(id).then(function(ifs){
        if(ifs && ifs.length){
            throw '模块下仍有接口,请先删除接口定义再删除模块';
        }
    }).then(function(){
        return dao.removeInterface(id);
    }).then(function(){
        res.end(JSON.stringify({suc : true}));
    }).catch(function(err){
        res.end(JSON.stringify({suc : false, err : err}));
    });
});

router.post('/delIf/:id', function(req, res){
    var id = req.params.id, dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    dao = daoHelper.getDao(pathInfo[1]);

    dao.removeInterfaceDetail(id).then(function(){
        return dao.removeInterface(id);
    }).then(function(){
        res.end(JSON.stringify({suc : true}));
    }).catch(function(err){
        res.end(JSON.stringify({suc : false, err : err}));
    })
});

router.post('/saveInterface', function (req, res, next) {
    var recObj = req.body, saveObj = {
        interfaceId : recObj.mId,
        code : recObj.code,
        name : recObj.name,
        order: recObj.order,
        parentId : recObj.parentId,
        depth: 1
    }, detailObj = {
        interfaceId : recObj.mId,
        interfaceCode : recObj.code,
        interfaceName : recObj.name,
        name : recObj.name,
        url : recObj.url,
        params : recObj['params[]'],
        paramType : recObj.paramType || 0,
        desc : recObj.desc,
        resultDemo : recObj.resultDemo,
        resultPage : recObj.resultPage,
        ifType : recObj.ifType,
        author : recObj.author,
        attrInfos : recObj['attrInfos[]']
    }, promise, dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    if(!pathInfo){
        res.render('error', {
            message: 'invalid path',
            error: req.originalUrl
        });
        return;
    }

    dao = daoHelper.getDao(pathInfo[1]);


    if(saveObj.interfaceId){
        promise = dao.updateModule(saveObj).then(function(){
            return dao.updateInterface(detailObj);
        });
    }else{
        detailObj.interfaceId = saveObj.interfaceId = commonUtil.uuid(16, 16);
        detailObj.createDate = saveObj.createDate = new Date();
        promise = dao.saveModule(saveObj).then(function(){
            return dao.saveInterface(detailObj);
        });
    }

    promise.then(function(){
        if(detailObj.ifType === 'jsp'){
            beanUtil.getBean('JspApiService').onUpdateDoc(pathInfo[1], detailObj.url);
        }
        res.end(JSON.stringify({suc : true}));
    }).then(null, function(err){
        res.end(JSON.stringify({suc : false, err : err}));
    });
});

router.get('/getIf/:id', function (req, res, next) {
    var result, id = req.params.id, dao, pathInfo = pathVarRegx.exec(req.originalUrl);
    if(!pathInfo){
        res.render('error', {
            message: 'invalid path',
            error: req.originalUrl
        });
        return;
    }

    dao = daoHelper.getDao(pathInfo[1]);

    dao.getModuleById(id).then(function(m){
        result = m.toObject();
        return dao.getInterfaceById(id);
    }).then(function(i){
        result.detailInfo = i;
        return result;
    }).then(function(){
        res.end(JSON.stringify({suc : true, result : result }));
    }).then(null, function(err){
        res.end(JSON.stringify({suc : false, err : err}));
    });
});

module.exports = router;
